package com.xinsoft.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xinsoft.common.exception.BDException;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.InOrOutStock;
import com.xinsoft.entity.dto.ScmProduceReturnDTO;
import com.xinsoft.entity.dto.ScmProduceReturnParam;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.ScmProduceReturnPageVo;
import com.xinsoft.entity.vo.ScmProduceReturnVo;
import com.xinsoft.mapper.ScmProduceReturnItemMapper;
import com.xinsoft.service.*;
import com.xinsoft.mapper.ScmProduceReturnMapper;
import com.xinsoft.utils.TokenUtil;
import lombok.Synchronized;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @author ZYM
* @description 针对表【scm_produce_return(生产退料)】的数据库操作Service实现
* @createDate 2023-08-14 11:30:38
*/
@Service
public class ScmProduceReturnServiceImpl extends ServiceImpl<ScmProduceReturnMapper, ScmProduceReturn>
    implements ScmProduceReturnService{
    @Resource
    private ScmProduceReturnItemMapper produceReturnItemMapper;

    @Autowired
    private ScmProduceReturnItemService produceReturnItemService;
    @Autowired
    private ScmStockService stockService;
    @Autowired
    private ScmStockHisService stockHisService;
    @Autowired
    private SysDocumentNumService sysDocumentNumService;

    @Override
    public IPage<ScmProduceReturnPageVo> findPageListByParam(ScmProduceReturnParam param) {
        Page<ScmProduceReturnPageVo> page = new Page<>(param.getCurrentPage(), param.getPageSize());
        IPage<ScmProduceReturnPageVo> pageList = baseMapper.findListByParam(page, param);
        return pageList;
    }

    @Override
    public List<ScmProduceReturnPageVo> findListByParam(ScmProduceReturnParam param) {
        List<ScmProduceReturnPageVo> list = baseMapper.findListByParam(param);
        return list;
    }

    @Override
    public Integer tempSave(ScmProduceReturnDTO dto) {
        ScmProduceReturn produceReturn = new ScmProduceReturn();
        BeanUtils.copyProperties(dto, produceReturn);
        produceReturn.setAuditStatus(Const.AUDIT_STATUS_WAIT);
        // produceReturn.setDoClose(Const.CloseStatus.NOT_CLOSED);
        List<ScmProduceReturnItem> itemList = dto.getScmProduceReturnItemList();
        // 保存或新增
        if (Objects.isNull(produceReturn.getId())) {
            // 更新流水号
            sysDocumentNumService.incrementLastSerialByDocumentId(Const.DOCUMENT_ID.PRODUCE_RETURN_DOCUMENT);
            this.save(produceReturn);
        } else {
            produceReturnItemService.remove(Wrappers.lambdaQuery(ScmProduceReturnItem.class).eq(ScmProduceReturnItem::getProduceReturnId, produceReturn.getId()));
            this.updateById(produceReturn);
        }

        // 保存生产入库明细
        itemList.forEach(item -> item.setProduceReturnId(produceReturn.getId()));
        produceReturnItemService.saveBatch(itemList);

        return produceReturn.getId();
    }

    @Override
    public ScmProduceReturnVo detail(Integer id) {
        ScmProduceReturnVo vo = baseMapper.getById(id);
        vo.setScmProduceReturnItemList(produceReturnItemMapper.listByProduceReturnId(id));
        return vo;
    }

    @Override
    public void del(List<Integer> ids) {
        List<ScmProduceReturn> list = this.list(Wrappers.lambdaQuery(ScmProduceReturn.class)
                .eq(ScmProduceReturn::getAuditStatus, Const.AUDIT_STATUS_NORMAL)
                .in(ScmProduceReturn::getId, ids));
        if (list.size() > 0) {
            throw new BDException("操作失败，只能删除未审核的生产退料单");
        }
        produceReturnItemService.remove(Wrappers.lambdaQuery(ScmProduceReturnItem.class).in(ScmProduceReturnItem::getProduceReturnId, ids));
        this.removeByIds(ids);
    }

    @Override
    public void audit(Integer id) {
        ScmProduceReturn produceReturn = this.getById(id);
        if (Const.AUDIT_STATUS_NORMAL.equals(produceReturn.getAuditStatus())) {
            throw new BDException("该单据已审核，无需重复审核");
        }
        produceReturn.setAuditId(TokenUtil.getUserId());
        produceReturn.setAuditTime(new Date());
        produceReturn.setAuditStatus(Const.AUDIT_STATUS_NORMAL);
        this.updateById(produceReturn);
        // 更新库存
        List<InOrOutStock> inOrOutStockList = this.getInOrOutStockList(id);
        stockService.updateInventory(Const.SourceBillType.SCTL, produceReturn.getReturnCode(), inOrOutStockList, Const.ChangeType.ADD);
    }

    @Override
    public void reverseAudit(Integer id) {
        ScmProduceReturn produceReturn = this.getById(id);
        if (Const.AUDIT_STATUS_WAIT.equals(produceReturn.getAuditStatus())) {
            throw new BDException("该单据未审核，无需反审核");
        }
        // int citeCount = purchaseInstockMapper.getPurchaseReturnCiteCount(id);
        // if (citeCount > 0) {
        //     throw new BDException("该单据已产生下游单据，不能反审核");
        // }
        produceReturn.setAuditId(null);
        produceReturn.setAuditTime(null);
        produceReturn.setAuditStatus(Const.AUDIT_STATUS_WAIT);
        this.updateById(produceReturn);
        // 更新库存
        List<InOrOutStock> inOrOutStockList = this.getInOrOutStockList(id);
        stockService.updateInventory(Const.SourceBillType.SCTL, produceReturn.getReturnCode(), inOrOutStockList, Const.ChangeType.SUBTRACT);
    }

    /**
     * 获取出入库明细列表
     * @param id
     * @return {@link List}<{@link InOrOutStock}>
     */
    public List<InOrOutStock> getInOrOutStockList(Integer id) {
        List<InOrOutStock> list = new ArrayList<>();
        List<ScmProduceReturnItem> items = produceReturnItemService.list(Wrappers.lambdaQuery(ScmProduceReturnItem.class).eq(ScmProduceReturnItem::getProduceReturnId, id));
        items.forEach(item -> {
            InOrOutStock inOrOutStock = new InOrOutStock();
            BeanUtils.copyProperties(item,inOrOutStock);
            inOrOutStock.setQty(item.getReturnNum());
            list.add(inOrOutStock);
        });
        return list;
    }

    @Override
    public void saveAudit(ScmProduceReturnDTO dto) {
        // 保存
        Integer id = this.tempSave(dto);
        // 审核
        this.audit(id);
    }

}




